<template>
  <div class="inventory-turnover-report">
    <!-- 搜索过滤区域 -->
    <div class="filter-container">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="商品分类">
          <el-select v-model="filterForm.categoryId" placeholder="选择分类" clearable>
            <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库">
          <el-select v-model="filterForm.warehouseId" placeholder="选择仓库" clearable>
            <el-option v-for="warehouse in warehouses" :key="warehouse.id" :label="warehouse.name" :value="warehouse.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :shortcuts="dateShortcuts"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 周转率概览卡片 -->
    <div class="summary-cards">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card shadow="hover" class="summary-card">
            <div class="summary-item">
              <div class="summary-icon turnover-icon">
                <el-icon><Timer /></el-icon>
              </div>
              <div class="summary-content">
                <div class="summary-title">平均周转率</div>
                <div class="summary-value">{{ formatNumber(averageTurnoverRate) }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="hover" class="summary-card">
            <div class="summary-item">
              <div class="summary-icon days-icon">
                <el-icon><Calendar /></el-icon>
              </div>
              <div class="summary-content">
                <div class="summary-title">平均周转天数</div>
                <div class="summary-value">{{ averageTurnoverDays }} 天</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="hover" class="summary-card">
            <div class="summary-item">
              <div class="summary-icon outbound-icon">
                <el-icon><Box /></el-icon>
              </div>
              <div class="summary-content">
                <div class="summary-title">总出库量</div>
                <div class="summary-value">{{ totalOutbound }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- 周转率表格 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%; margin-top: 20px;"
      v-loading="loading"
      :default-sort="{ prop: 'turnoverRate', order: 'descending' }"
      @sort-change="handleSortChange"
    >
      <el-table-column prop="id" label="ID" width="80" sortable />
      <el-table-column prop="name" label="商品名称" min-width="200" sortable show-overflow-tooltip />
      <el-table-column prop="sku" label="SKU" width="120" sortable show-overflow-tooltip />
      <el-table-column label="分类" width="120">
        <template #default="scope">
          {{ scope.row.category ? scope.row.category.name : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="stockQuantity" label="当前库存" width="120" sortable>
        <template #default="scope">
          <span>{{ scope.row.stockQuantity || 0 }} {{ scope.row.stockUnit }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="totalOutbound" label="出库量" width="120" sortable>
        <template #default="scope">
          <span>{{ scope.row.totalOutbound || 0 }} {{ scope.row.stockUnit }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="averageStock" label="平均库存" width="120" sortable>
        <template #default="scope">
          <span>{{ scope.row.averageStock || 0 }} {{ scope.row.stockUnit }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="turnoverRate" label="周转率" width="120" sortable>
        <template #default="scope">
          <span :class="getTurnoverRateClass(scope.row.turnoverRate)">
            {{ formatNumber(scope.row.turnoverRate) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="turnoverDays" label="周转天数" width="120" sortable>
        <template #default="scope">
          <span :class="getTurnoverDaysClass(scope.row.turnoverDays)">
            {{ scope.row.turnoverDays || 0 }} 天
          </span>
        </template>
      </el-table-column>
      <el-table-column label="周转评级" width="120">
        <template #default="scope">
          <el-tag :type="getTurnoverRateTag(scope.row.turnoverRate)">
            {{ getTurnoverRateLevel(scope.row.turnoverRate) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="scope">
          <el-button 
            type="primary" 
            size="small" 
            @click="goToProductDetail(scope.row.id)"
          >
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, watch, inject } from 'vue';
import { useRouter } from 'vue-router';
import { getInventoryTurnoverReport } from '@/api/inventory';
import { getAllCategories } from '@/api/category';
import { getAllWarehouses } from '@/api/inventory';

export default {
  name: 'InventoryTurnoverReport',
  emits: ['loading-change'],
  setup(props, { emit }) {
    const router = useRouter();
    const loading = inject('loading', ref(false));
    
    // 表格数据
    const tableData = ref([]);
    const categories = ref([]);
    const warehouses = ref([]);
    
    // 日期范围
    const dateRange = ref([]);
    
    // 过滤条件
    const filterForm = reactive({
      categoryId: null,
      warehouseId: null,
      startDate: null,
      endDate: null,
      sortBy: 'turnoverRate',
      sortOrder: 'desc'
    });
    
    // 日期快捷选项
    const dateShortcuts = [
      {
        text: '最近一周',
        value: () => {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
          return [start, end];
        }
      },
      {
        text: '最近一个月',
        value: () => {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
          return [start, end];
        }
      },
      {
        text: '最近三个月',
        value: () => {
          const end = new Date();
          const start = new Date();
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
          return [start, end];
        }
      }
    ];
    
    // 监听日期范围变化
    watch(dateRange, (newVal) => {
      if (newVal && newVal.length === 2) {
        filterForm.startDate = newVal[0];
        filterForm.endDate = newVal[1];
      } else {
        filterForm.startDate = null;
        filterForm.endDate = null;
      }
    });
    
    // 计算平均周转率
    const averageTurnoverRate = computed(() => {
      if (!tableData.value || tableData.value.length === 0) {
        return 0;
      }
      
      const sum = tableData.value.reduce((acc, item) => acc + (parseFloat(item.turnoverRate) || 0), 0);
      return sum / tableData.value.length;
    });
    
    // 计算平均周转天数
    const averageTurnoverDays = computed(() => {
      if (!tableData.value || tableData.value.length === 0) {
        return 0;
      }
      
      // 过滤掉周转天数为0的商品
      const validItems = tableData.value.filter(item => item.turnoverDays > 0);
      
      if (validItems.length === 0) {
        return 0;
      }
      
      const sum = validItems.reduce((acc, item) => acc + (parseInt(item.turnoverDays) || 0), 0);
      return Math.round(sum / validItems.length);
    });
    
    // 计算总出库量
    const totalOutbound = computed(() => {
      if (!tableData.value || tableData.value.length === 0) {
        return 0;
      }
      
      return tableData.value.reduce((acc, item) => acc + (parseFloat(item.totalOutbound) || 0), 0);
    });
    
    // 获取周转率评级标签
    const getTurnoverRateTag = (rate) => {
      if (rate >= 3) {
        return 'success';
      } else if (rate >= 1) {
        return 'primary';
      } else if (rate >= 0.5) {
        return 'warning';
      } else {
        return 'danger';
      }
    };
    
    // 获取周转率评级文本
    const getTurnoverRateLevel = (rate) => {
      if (rate >= 3) {
        return '优秀';
      } else if (rate >= 1) {
        return '良好';
      } else if (rate >= 0.5) {
        return '一般';
      } else {
        return '较差';
      }
    };
    
    // 获取周转率样式类
    const getTurnoverRateClass = (rate) => {
      if (rate >= 3) {
        return 'rate-excellent';
      } else if (rate >= 1) {
        return 'rate-good';
      } else if (rate >= 0.5) {
        return 'rate-normal';
      } else {
        return 'rate-poor';
      }
    };
    
    // 获取周转天数样式类
    const getTurnoverDaysClass = (days) => {
      if (days <= 30) {
        return 'days-excellent';
      } else if (days <= 90) {
        return 'days-good';
      } else if (days <= 180) {
        return 'days-normal';
      } else {
        return 'days-poor';
      }
    };
    
    // 格式化数字，保留两位小数
    const formatNumber = (num) => {
      return parseFloat(num || 0).toFixed(2);
    };
    
    // 获取库存周转率报表数据
    const fetchData = async () => {
      emit('loading-change', true);
      try {
        // 构建查询参数
        const params = { ...filterForm };
        
        const response = await getInventoryTurnoverReport(params);
        tableData.value = response.data || [];
      } catch (error) {
        console.error('获取库存周转率报表失败:', error);
      } finally {
        emit('loading-change', false);
      }
    };
    
    // 加载基础数据
    const loadBaseData = async () => {
      try {
        const [categoriesRes, warehousesRes] = await Promise.all([
          getAllCategories(),
          getAllWarehouses()
        ]);
        
        categories.value = categoriesRes.data || [];
        warehouses.value = warehousesRes.data || [];
      } catch (error) {
        console.error('加载基础数据失败:', error);
      }
    };
    
    // 查询按钮事件处理
    const handleSearch = () => {
      fetchData();
    };
    
    // 重置按钮事件处理
    const handleReset = () => {
      Object.keys(filterForm).forEach(key => {
        if (key !== 'sortBy' && key !== 'sortOrder') {
          filterForm[key] = null;
        }
      });
      dateRange.value = [];
      fetchData();
    };
    
    // 表格排序变化事件处理
    const handleSortChange = ({ prop, order }) => {
      if (prop) {
        filterForm.sortBy = prop;
        filterForm.sortOrder = order === 'ascending' ? 'asc' : 'desc';
        fetchData();
      }
    };
    
    // 跳转到商品详情
    const goToProductDetail = (id) => {
      router.push(`/admin/inventory/product/${id}`);
    };
    
    // 获取导出参数
    const getExportParams = () => {
      return { ...filterForm };
    };
    
    onMounted(() => {
      loadBaseData();
      fetchData();
      
      // 设置默认日期范围为最近30天
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      dateRange.value = [start.toISOString().split('T')[0], end.toISOString().split('T')[0]];
    });
    
    return {
      loading,
      tableData,
      categories,
      warehouses,
      filterForm,
      dateRange,
      dateShortcuts,
      averageTurnoverRate,
      averageTurnoverDays,
      totalOutbound,
      getTurnoverRateTag,
      getTurnoverRateLevel,
      getTurnoverRateClass,
      getTurnoverDaysClass,
      formatNumber,
      fetchData,
      handleSearch,
      handleReset,
      handleSortChange,
      goToProductDetail,
      getExportParams
    };
  }
};
</script>

<style scoped>
.inventory-turnover-report {
  margin-top: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.summary-cards {
  margin-bottom: 20px;
}

.summary-card {
  transition: all 0.3s;
}

.summary-card:hover {
  transform: translateY(-5px);
}

.summary-item {
  display: flex;
  align-items: center;
}

.summary-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 15px;
}

.summary-icon .el-icon {
  font-size: 24px;
  color: white;
}

.turnover-icon {
  background-color: #409EFF;
}

.days-icon {
  background-color: #67C23A;
}

.outbound-icon {
  background-color: #E6A23C;
}

.summary-content {
  flex: 1;
}

.summary-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.summary-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.rate-excellent {
  color: #67C23A;
  font-weight: bold;
}

.rate-good {
  color: #409EFF;
  font-weight: bold;
}

.rate-normal {
  color: #E6A23C;
  font-weight: bold;
}

.rate-poor {
  color: #F56C6C;
  font-weight: bold;
}

.days-excellent {
  color: #67C23A;
  font-weight: bold;
}

.days-good {
  color: #409EFF;
  font-weight: bold;
}

.days-normal {
  color: #E6A23C;
  font-weight: bold;
}

.days-poor {
  color: #F56C6C;
  font-weight: bold;
}

@media print {
  .filter-container {
    display: none !important;
  }
}
</style> 